<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use Carbon\Carbon;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Work extends Auth
{
    public $noNeedLogin = [];


    /**
     * 检测当日打卡状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check(){
        if($this->request->isPost()){
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if(empty($getData['time']) || !isset($getData['time'])){
                $this->result('缺少参数', '', 204);
            }
            $time = explode('-',$getData['time']);
            $week = Carbon::create($time[0], $time[1], $time[2])->dayOfWeekIso;
            //获取用户每天打卡次数
            $workId = Db::name('qt_post_work')->where('post_id',$userInfo['post_id'])->value('work_id');
            $workRes = Db::name('qt_work')->where('id',$workId)->find();
            //查询周一到周日的打卡时间
            $workNum = Db::name('qt_work_num')
                ->where('work_id',$workRes['id'])
                ->where('week',$week)
                ->order('week asc')
                ->group('week')
                ->find();
            //查询今日的打卡次数
            $count = Db::name('qt_work_log')
                ->where(['user_id'=>$userInfo['id'],'group_id'=>$userInfo['group_id'],'day'=>$getData['time'],'week'=>$week])
                ->whereIn('type','1,2,3,5,7,9')
                ->count();
            //正常上班
            if($workNum['type'] == '1'){
                if($count == $workRes['work_num']){
                    $result['status'] = '1'; //打卡正常
                    $result['data'] = []; //打卡正常
                }else{
                    $data = Db::name('qt_work_log')
                        ->field('id,created_time')
                        ->where(['user_id'=>$userInfo['id'],'group_id'=>$userInfo['group_id'],'day'=>$getData['time'],'week'=>$week])
                        ->whereIn('type','0,4')
                        ->select();
                    $result['status'] = '0'; //打卡异常
                    $result['data'] = $data; //打卡异常
                }
            }else{
                //休息日
                $result['status'] = '1'; //打卡正常
                $result['data'] = []; //打卡正常
            }
            $this->result('请求成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);

    }


    /**
     * 统计当前用户昨天的打卡
     */
    public function getyesterday(){
        $userInfo = $this->userInfo;
        $time = Carbon::yesterday()->toDateString();
        $week = Carbon::yesterday()->dayOfWeekIso;
        $workConfig = Db::name('qt_work')->where(['store_id'=>$userInfo['store_id'],'post_id'=>$userInfo['post_id'],'status'=>'1'])->find();
        if($workConfig){
            $work = Db::name('qt_work_num')->where(['work_id'=>$workConfig['id'],'week'=>$week])->find();
            if($work['type'] == '1'){
                $workLog = Db::name('qt_work_log')->where(['user_id'=>$userInfo['id'],'day'=>$time])->select();
                foreach ($workLog as $key=>$value){
                    if(empty($value['clock_time']) || $value['type'] == '0'){
                        Db::name('qt_work_log')->where('id',$value['id'])->update(['type'=>'4']);
                    }
                }
                //开始时间
                $startRes = Db::name('qt_work_log')->where(['user_id'=>$userInfo['id'],'day'=>$time])->order('created_time asc')->find();
                if(empty($startRes['clock_time'])){
                    $duration = '0';
                }else{
                    $endRes = Db::name('qt_work_log')->where(['user_id'=>$userInfo['id'],'day'=>$time])->order('created_time desc')->find();
                    if(empty($endRes['clock_time'])){
                        $duration = '0';
                    }else{
                        $timeDuration = ($endRes['clock_time'] - $startRes['clock_time']) / 3600;
                        $duration = round($timeDuration,1);
                    }

                }
                //结束时间
                foreach ($workLog as $key=>$value){
                    if(empty($value['clock_time']) || $value['type'] == '0'){
                        Db::name('qt_work_log')->where('id',$value['id'])->update(['duration'=>$duration]);
                    }
                }
            }
        }
    }


    /**
     * 获取考勤登记列表
     */
    public function attendance(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['limit']) || empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $sql = Db::name('qt_work_attendance')
                ->alias('a')
                ->leftJoin('qt_users u','u.id = a.user_id')
                ->field('a.id,a.group,a.engineer_id,a.reason,a.rank,a.start_time,a.end_time,a.handle_time,a.day,a.reason,a.rank,u.real_name,a.create_time,a.status')
                ->where('a.store_id',$this->userInfo['store_id']);
            //时间筛选
            if(isset($getData['time_type']) && !empty($getData['time_type'])){
                //开始时间
                if($getData['time_type'] == '1'){
                    if(isset($getData['start_time']) && !empty($getData['start_time']) && isset($getData['end_time']) && !empty($getData['end_time'])){
                        $start_time = strtotime($getData['start_time']);
                        $end_time = strtotime($getData['end_time']);
                        $sql = $sql->whereBetweenTime('a.create_time',$start_time,$end_time);
                    }
                }
                //结束时间
                if($getData['time_type'] == '2'){
                    //时间筛选
                    if(isset($getData['start_time']) && !empty($getData['start_time']) && isset($getData['end_time']) && !empty($getData['end_time'])){
                        $start_time = strtotime($getData['start_time']);
                        $end_time = strtotime($getData['end_time']);
                        $sql = $sql->whereBetweenTime('a.handle_time',$start_time,$end_time);
                    }
                }
            }
            //部门筛选
            if (isset($getData['group']) && !empty($getData['group']))
            {
                $sql = $sql->where('a.group',$getData['group']);
            }
            //请假人
            if (isset($getData['engineer_id']) && !empty($getData['engineer_id']))
            {
                $sql = $sql->where('a.engineer_id',$getData['engineer_id']);
            }

            //原因
            if (isset($getData['reason']) && !empty($getData['reason']))
            {
                $sql = $sql->where('a.reason',$getData['reason']);
            }

            //登记人
            if (isset($getData['user_id']) && !empty($getData['user_id']))
            {
                $sql = $sql->where('a.user_id',$getData['user_id']);
            }

            //状态
            if (isset($getData['status']) && !empty($getData['status']))
            {
                $sql = $sql->where('a.status',$getData['status']);
            }
            $data = $sql->order('a.id desc')
                ->paginate($getData['limit'])->each(function ($item){
                    $engineerRes = Db::name('qt_users')->where('id',$item['engineer_id'])->find();
                    $item['work_number'] = $engineerRes['work_number'];
                    $item['engineer_name'] = $engineerRes['real_name'];
                    return $item;
                });
            $this->result('请求成功', $data, 200);
        }
    }

    /**
     * 删除考勤登记
     */
    public function attendance_remove(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数','',204);
            }
            $del = Db::name('qt_work_attendance')->where('id',$getData['id'])->delete();
            if($del){
                $this->result('删除成功','',200);
            }
            $this->result('删除失败','',204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 销假
     */
    public function attendance_destroy(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id']) || empty($getData['status'])){
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_work_attendance')->where('id',$getData['id'])->find();
            try{
                Db::startTrans();
                //销假
                Db::name('qt_work_attendance')->where('id',$getData['id'])->update(['status'=>$getData['status'],'handle_time'=>time()]);
                $userStatus = Db::name('qt_users')->where(['id'=>$data['engineer_id']])->value('work_status');
                if($userStatus == '7'){
                    Db::name('qt_users')->where('id',$data['engineer_id'])->update(['work_status'=>'1']);
                }
                Db::commit();
            }catch (Exception $exception) {
                Db::rollback();
                $this->result('修改失败', '', 204);
            }
            $this->result('修改成功','',200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取员工打卡记录
     */
    public function clock_log(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['limit']) || empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $getData['time'] = !empty($getData['time']) ? $getData['time'] : 1;
            $query = Db::name('qt_work_log')
                ->alias('l')
                ->leftJoin('qt_users u','u.id = l.user_id')
                ->field('l.id,l.type,l.work_type,l.created_time,l.day,u.real_name,u.work_number,u.group,l.address,l.user_id')
                ->where('u.store_id',$this->userInfo['store_id']);
            //时间筛选
            if(!empty($getData['start_time']) && !empty($getData['end_time'])){
                $start_time = strtotime($getData['start_time']);
                $end_time = strtotime($getData['end_time']);
                $query = $query->whereBetweenTime('l.created_time',$start_time,$end_time);
            }
            //部门筛选
            if (!empty($getData['group'])) {
                $query = $query->where('u.group',$getData['group']);
            }
            //人员筛选
            if (isset($getData['user_id']) && !empty($getData['user_id']))
            {
                $query->where('u.id',$getData['user_id']);
            }
            $data = $query->group('l.user_id')
                ->paginate($getData['limit'])->each(function ($item) use($getData){
                $start_time = strtotime($getData['start_time']);
                $end_time = strtotime($getData['end_time']);
                $start = Db::name('qt_work_log')
                    ->where('store_id',$this->userInfo['store_id'])
                    ->whereBetweenTime('created_time',$start_time,$end_time)
                    ->min('created_time');
                $end = Db::name('qt_work_log')
                    ->where('store_id',$this->userInfo['store_id'])
                    ->whereBetweenTime('created_time',$start_time,$end_time)
                    ->max('created_time');
                $item['duration'] = number_format(($end - $start) / 3600,1);
                if(!empty($item['other_user_id'])){
                    $item['other_user_name'] = Db::name('qt_users')->where(['id'=>$item['other_user_id']])->value('real_name');
                }else{
                    $item['other_user_name'] = '';
                }
                return $item;
            });
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 添加考勤登记
     */
    public function attendance_add(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\Attendance();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $getData['store_id'] = $this->userInfo['store_id'];
            $getData['user_id'] = $this->userInfo['id'];
            $getData['status'] = '1';
            $getData['create_time'] = time();
            try{
                Db::startTrans();
                //插入请假数据
                Db::name('qt_work_attendance')->insert($getData);
                $userStatus = Db::name('qt_users')->where(['id'=>$getData['engineer_id']])->value('work_status');
                if($userStatus == '1'){
                    //更新用户请假
                    Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'7']);
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('添加失败','',204);
            }
            $this->result('添加成功','',200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 修改考勤登记
     */
    public function attendance_edit(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数','',204);
            }
            $find = Db::name('qt_work_attendance')->where('id',$getData['id'])->find();
            if(!empty($find)){
                $userRes = Db::name('qt_users')->where('id',$find['user_id'])->find();
                $engineerRes = Db::name('qt_users')->where('id',$find['engineer_id'])->find();
                $find['real_name'] = $userRes['real_name'];
                $find['work_number'] = $engineerRes['work_number'];
                $find['engineer_name'] = $engineerRes['real_name'];
            }
            $this->result('查询成功', $find, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 修改考勤登记
     */
    public function attendance_save(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\Attendance();
            if (!$validate->scene('edit')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $getData['store_id'] = $this->userInfo['store_id'];
            $getData['user_id'] = $this->userInfo['id'];
            $getData['status'] = '1';
            unset($getData['create_time']);
            $inset = Db::name('qt_work_attendance')->where('id',$getData['id'])->update($getData);
            if($inset){
                $this->result('修改成功','',200);
            }
            $this->result('修改失败','',204);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 考勤记录
     */
    public function attendance_total(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $sql = Db::name('qt_work_attendance')
                ->alias('a')
                ->leftJoin('qt_users u','u.id = a.engineer_id')
                ->field('a.id,a.group,u.real_name,u.work_number,a.engineer_id')
                ->where('a.store_id',$this->userInfo['store_id']);
            $map=array();
            $maps=array();
            if(isset($getData['start_time']) && !empty($getData['start_time']) && isset($getData['end_time']) && !empty($getData['end_time'])){
                $start_time = strtotime($getData['start_time']);
                $end_time = strtotime($getData['end_time']);
                $map[]=['a.create_time','between time',[$start_time,$end_time]];
                $maps[]=['create_time','between time',[$start_time,$end_time]];
                //$sql = $sql->whereBetweenTime('a.create_time',$start_time,$end_time);
            }
            //部门筛选
            if (isset($getData['group']) && !empty($getData['group']))
            {
                $map[]=['a.group','eq',$getData['group']];
                $maps[]=['group','eq',$getData['group']];
//                $sql = $sql->where('a.group',$getData['group']);
            }
            if(!isset($getData['limit']) || empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $engineerRes = $sql->where($map)->group('a.engineer_id')
                ->paginate($getData['limit'])
                ->each(function ($item) use( $maps,$getData) {
                    $item['baoting']['number'] = Db::name('qt_work_attendance')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','1')->sum('day');
                    $item['baoting']['list'] = Db::name('qt_work_attendance')->field('start_time,end_time')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','1')->select();
                    $item['qingjia']['number'] = Db::name('qt_work_attendance')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','2')->sum('day');
                    $item['qingjia']['list'] = Db::name('qt_work_attendance')->field('start_time,end_time')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','2')->select();
                    $item['bingjia']['number'] = Db::name('qt_work_attendance')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','3')->sum('day');
                    $item['bingjia']['list'] = Db::name('qt_work_attendance')->field('start_time,end_time')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','3')->select();

                    $item['xiuxi']['number'] = Db::name('qt_work_attendance')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','4')->sum('day');
                    $item['xiuxi']['list'] = Db::name('qt_work_attendance')->field('start_time,end_time')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','4')->select();

                    $item['xiujia']['number'] = Db::name('qt_work_attendance')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','5')->sum('day');
                    $item['xiujia']['list'] = Db::name('qt_work_attendance')->field('start_time,end_time')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','5')->select();

                    $item['kuanggong']['number'] = Db::name('qt_work_attendance')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','6')->sum('day');
                    $item['kuanggong']['list'] = Db::name('qt_work_attendance')->field('start_time,end_time')->where($maps)->where('engineer_id',$item['engineer_id'])->where('reason','6')->select();
                    $item['total'] = $item['baoting']['number'] + $item['qingjia']['number']+ $item['bingjia']['number']+ $item['xiuxi']['number']+ $item['xiujia']['number']+ $item['kuanggong']['number'];
                    $item['start_time'] = $getData['start_time'];
                    $item['end_time'] = $getData['end_time'];
                    return $item;
                });
            $this->result('请求成功', $engineerRes, 200);

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 团队用户统计
     */
    public function yesterdayTeam(){
        $userInfo = $this->userInfo;
        if($userInfo['rank' == '1']){
            $this->result('获取成功', '', 200);
        }
        if($userInfo['rank' == '3']){
            $this->result('获取成功', '', 200);
        }
        $time = Carbon::yesterday()->toDateString();
        $week = Carbon::yesterday()->dayOfWeekIso;
        //判断是否存在，如果存在则删除统计
        $find = Db::name('qt_work_team')->where(['user_id'=>$userInfo['id'],'day'=>$time,'type'=>'1'])->find();
        if($find){
            Db::name('qt_work_team')->where(['id'=>$find['id']])->delete();
            Db::name('qt_work_team_log')->where(['work_team_id'=>$find['id']])->delete();
        }
        //创建数据
        $pidRes = Db::name('qt_post')->where('post_pid',$userInfo['post_id'])->column('id');
        $userRes = Db::name('qt_users')
            ->alias('u')
            ->leftJoin('qt_post p','p.id = u.post_id')
            ->field('u.id,u.nickname')
            ->where('u.team_id',$userInfo['team_id'])
            ->whereIn('p.id',$pidRes)
            ->select();
        //插入用户团队打卡
        $insert['user_id'] = $userInfo['id'];
        $insert['group_id'] = $userInfo['group_id'];
        $insert['week'] = $week;
        $insert['total_num'] = count($userRes);
        $insert['day'] = $time;
        $insert['day'] = $time;
        $insert['day'] = $time;
        $insert['type'] = '1';
        static $late = 0;//迟到
        static $missing = 0;//缺卡
        static $leave = 0;//请假
        static $absenteeism = 0;//旷工
        static $over = 0;//加班
        static $field = 0;//早退
        static $totalDuration = 0;//时长
        $workTeamID = Db::name('qt_work_team')->insertGetId($insert);
        //处理用户打卡记录
        $i = 0;
        foreach ($userRes as $key=>$value){
            $workLog = Db::name('qt_work_log')->where(['day'=>$time,'user_id'=>$value['id']])->group('day')->select();
            //开始时间
            $startRes = Db::name('qt_work_log')->where(['user_id'=>$userInfo['id'],'day'=>$time])->order('created_time asc')->find();
            if(empty($startRes['clock_time'])){
                $duration = '0';
            }else{
                $endRes = Db::name('qt_work_log')->where(['user_id'=>$userInfo['id'],'day'=>$time])->order('created_time desc')->find();
                if(empty($endRes['clock_time'])){
                    $duration = '0';
                }else{
                    $timeDuration = ($endRes['clock_time'] - $startRes['clock_time']) / 3600;
                    $duration = round($timeDuration,1);
                }
            }
            //获取有效的数据
            if($duration != '0'){
                $i++;
                $totalDuration += $duration;
            }
            foreach ($workLog as $k=>$v){
                //查询迟到
                $chiao = Db::name('qt_work_log')->where(['day'=>$v['day'],'user_id'=>$v['user_id'],'type'=>'2'])->find();
                if(!empty($chiao)){
                    $late += 1;
                    $log['work_team_id'] = $workTeamID;
                    $log['user_id'] = $v['user_id'];
                    $log['time'] = $chiao['clock_time'];
                    $log['type'] = '2';
                    Db::name('qt_work_team_log')->insert($log);
                }
                //缺卡
                $queka = Db::name('qt_work_log')->where(['day'=>$v['day'],'user_id'=>$v['user_id'],'type'=>'4'])->find();
                if(!empty($queka)){
                    $missing += 1;
                    $quekalog['work_team_id'] = $workTeamID;
                    $quekalog['user_id'] = $v['user_id'];
                    $quekalog['time'] = $queka['created_time'];
                    $quekalog['type'] = '4';
                    Db::name('qt_work_team_log')->insert($quekalog);
                }
                //请假
                $qingjia = Db::name('qt_work_log')->where(['day'=>$v['day'],'user_id'=>$v['user_id'],'type'=>'9'])->find();
                if(!empty($qingjia)){
                    $leave += 1;
                    $qingjialog['work_team_id'] = $workTeamID;
                    $qingjialog['user_id'] = $v['user_id'];
                    $qingjialog['time'] = $qingjia['created_time'];
                    $qingjialog['type'] = '9';
                    Db::name('qt_work_team_log')->insert($qingjialog);
                }
                //旷工
                $kuanggong = Db::name('qt_work_log')->where(['day'=>$v['day'],'user_id'=>$v['user_id'],'type'=>'6'])->find();
                if(!empty($kuanggong)){
                    $absenteeism += 1;
                    $kuanggonglog['work_team_id'] = $workTeamID;
                    $kuanggonglog['user_id'] = $v['user_id'];
                    $kuanggonglog['time'] = $kuanggong['created_time'];
                    $kuanggonglog['type'] = '6';
                    Db::name('qt_work_team_log')->insert($kuanggonglog);
                }

                //加班
                $jiaban = Db::name('qt_work_log')->where(['day'=>$v['day'],'user_id'=>$v['user_id'],'type'=>'8'])->find();
                if(!empty($jiaban)){
                    $over += 1;
                    $jiabanlog['work_team_id'] = $workTeamID;
                    $jiabanlog['user_id'] = $v['user_id'];
                    $jiabanlog['time'] = $jiaban['clock_time'];
                    $jiabanlog['type'] = '8';
                    Db::name('qt_work_team_log')->insert($jiabanlog);
                }
                //早退
                $zaotui = Db::name('qt_work_log')->where(['day'=>$v['day'],'user_id'=>$v['user_id'],'type'=>'5'])->find();
                if(!empty($zaotui)){
                    $field += 1;
                    $zaotuilog['work_team_id'] = $workTeamID;
                    $zaotuilog['user_id'] = $v['user_id'];
                    $zaotuilog['time'] = $zaotui['clock_time'];
                    $zaotuilog['type'] = '8';
                    Db::name('qt_work_team_log')->insert($zaotuilog);
                }

            }
        }
        //平均时长
        if($i != '0'){
            $duration = $totalDuration / $i;
        }else{
            $duration = '0';
        }
        $updata['duration'] = $duration;
        $updata['late'] = $late;
        $updata['missing'] = $missing;
        $updata['leave'] = $leave;
        $updata['absenteeism'] = $absenteeism;
        $updata['over'] = $over;
        $updata['field'] = $field;
        $up = Db::name('qt_work_team')->where(['id'=>$workTeamID])->update($updata);
        if($up){
            $this->result('获取昨日团队数据成功', '', 200);
        }
        $this->result('获取失败', '', 204);
    }



    /**
     * 考勤打卡说明
     */
    public function explain(){
        if ($this->request->isGet()) {
            //打卡位置
            $userInfo = $this->userInfo;
            $data = Db::name('qt_work')
                ->alias('w')
                ->field('w.time_rule,w.work_rule,w.repair_rule,wc.address,wc.distance')
                ->leftJoin('qt_work_config wc','wc.group_id = w.group_id')
                ->where(['w.group_id'=>$userInfo['group_id'],'w.post_id'=>$userInfo['post_id']])
                ->find();
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * @param $data
     */
    public function getData($userInfo,$data){
        $week = Carbon::now()->dayOfWeekIso;//星期
        //$day = Carbon::now()->toDateString();
        $day = strtotime(date('Y-m-d',time()));
        $startTime = $day.' '.$data['start_time'];
        $startTime = strtotime($startTime);
        $endTime = $day.' '.$data['end_time'];
        $endTime = strtotime($endTime);
        $insertData[0]['user_id'] = $userInfo['id'];
        $insertData[0]['store_id'] = $userInfo['store_id'];
        $insertData[0]['work_id'] = $data['work_id'];
        $insertData[0]['work_time_id'] = $data['id'];
        $insertData[0]['week'] =$week;
        $insertData[0]['day'] =$day;
        $insertData[0]['work_type'] ='1';
        $insertData[0]['created_time'] = $startTime;
        $insertData[0]['type'] = '0';
        $insertData[1]['user_id'] = $userInfo['id'];
        $insertData[1]['store_id'] = $userInfo['store_id'];
        $insertData[1]['work_id'] = $data['work_id'];
        $insertData[1]['work_time_id'] = $data['id'];
        $insertData[1]['week'] =$week;
        $insertData[1]['day'] =$day;
        $insertData[1]['work_type'] ='2';
        $insertData[1]['created_time'] = $endTime;
        $insertData[1]['type'] = '0';
        return $insertData;
    }


    /**
     * 获取无线网数据列表
     */
    public function wifiList(){
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_store_wifi')
                ->field('id,wifi,mac')
                ->where(['store_id'=>$userInfo['store_id']])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiAdd(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['wifi']) || empty($getData['wifi'])){
                $this->result('缺少参数', '', 204);
            }
            if(!isset($getData['mac']) || empty($getData['mac'])){
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_store_wifi')->where(['store_id'=>$this->userInfo['store_id'],'wifi'=>$getData['wifi']])->find();
            if(!empty($find)){
                $this->result('无线已经存在', '', 204);
            }
            $getData['created_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $data = Db::name('qt_store_wifi')->insert($getData);
            if($data){
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiDel(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['id']) || empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $del = Db::name('qt_store_wifi')->where('id',$getData['id'])->delete();
            if($del){
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 添加工种
     */
    public function add_type(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $insertData['store_id'] = $this->store_id;
            $insertData['title'] = $getData['title'];
            $insertData['pid'] = $getData['pid'];
            $insertData['sort'] = $getData['sort'];
            $insertData['created_time'] = time();
            $insert = Db::name('qt_work_type')->insert($insertData);
            if($insert){
                $this->result('添加成功','',200);
            }
            $this->result('添加失败','',204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 当天打卡记录
     */
    public function work_list(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $sql = Db::name('qt_work_log')
                ->where(['user_id'=>$this->userInfo['id'],'store_id'=>$this->store_id]);
            if(empty($getData['start_time']) || empty($getData['end_time'])){
                $this->result('缺少时间查询', '', 204);
            }
            //查询用户打卡记录
            $data = $sql->order('id desc')
                ->whereBetweenTime('created_time',strtotime($getData['start_time']),strtotime($getData['end_time']))
                ->select();
            $this->result('获取成功', $data, 200);
        }
    }




    /**
     * 获取用户打卡时间
     */
    public function work_config()
    {
        if ($this->request->isPost()) {
            $time = strtotime(date('Y-m-d'));
            //查询用户打卡记录
            $workLog = Db::name('qt_work_log')
                ->where(['user_id'=>$this->userInfo['id'],'store_id'=>$this->store_id,'day'=>$time])
                ->order('id desc')
                ->find();
            if(empty($workLog)){
                $result['work_status'] = '1';//上班卡
            }elseif($workLog['work_type'] == '1'){
                $result['work_status'] = '2';//下班卡
                $result['data'] = $workLog;
            }else{
                $result['work_status'] = '1';//上班卡
            }
            $this->result('获取成功', $result, 200);
        }
    }


    /**
     * 打卡
     */
    public function clock(){
        if ($this->request->isPost()) {
            //打卡位置
            $getData = $this->request->post();
            if(empty($getData['work_status']) || empty($getData['lat']) || empty($getData['lon'])){
                $this->result('缺少参数', '', 204);
            }
//            $userWifi = Db::name('qt_store_wifi')->where('store_id',$this->store_id)->column('wifi');
//            if(in_array($getData['wifi'],$userWifi)){
            $insertData  = $this->getWorkData($this->userInfo,time(),$getData['work_status']);
            if(!isset($getData['address'])){
                $address = '未知地址';
            }else{
                $address = $getData['address'];
            }
            $insertData['lat'] = $getData['lat'];
            $insertData['lon'] = $getData['lon'];
            $insertData['address'] = $address;
            $save = Db::name('qt_work_log')->insert($insertData);
            if($getData['work_status'] == '1'){
                Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['work_status'=>'1']);
            }
            if($getData['work_status'] == '2'){
                Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['work_status'=>'2']);
            }
            $this->result('打卡成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取员工打卡记录
     */
    public function user_clock_log(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['limit']) || empty($getData['limit'])){
                $getData['limit'] = '10';
            }
            $start_time = strtotime($getData['start_time']);
            $end_time = strtotime($getData['end_time']);

            $sql = Db::name('qt_work_log')
                ->alias('l')
                ->leftJoin('qt_users u','u.id = l.user_id')
                ->field('l.id,l.type,l.work_type,l.created_time,u.real_name,u.work_number,u.group')
                ->where('u.store_id',$this->userInfo['store_id'])
                ->where('u.id',$getData['user_id'])
                ->whereBetweenTime('l.created_time',$start_time,$end_time);
            $data = $sql->paginate( $getData['limit'])->each(function ($item){
                if(!empty($item['other_user_id'])){
                    $item['other_user_name'] = Db::name('qt_users')->where(['id'=>$item['other_user_id']])->value('real_name');
                }else{
                    $item['other_user_name'] = '';
                }
                return $item;
            });
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     *
     * 获取用户打卡时间
     * @param $userInfo
     * @param $time
     * @param $workStatus
     * @return array
     */
    public function getWorkData($userInfo,$time,$workStatus){
        $week = Carbon::now()->dayOfWeekIso;//星期
        $insertData['user_id'] = $userInfo['id'];
        $insertData['store_id'] = $userInfo['store_id'];
        $insertData['week'] =$week;
        $insertData['day'] =strtotime(date('Y-m-d')) ;
        $insertData['work_type'] =$workStatus;
        $insertData['created_time'] = $time;
        $insertData['type'] = '1';
        return $insertData;
    }




}
